import request from "../utils/request";
import { Toast } from "antd-mobile";

export default {
  namespace: "content",
  state: {
    pageSize: 1,
    totalList: [],
    cList: [],
    proid: "",
    proDetail: {},
    pageNum: 1,
    searchList: [],
    queryListDe: [],
    backflag: 1,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, history }) => {
        if (pathname === "/") {
          window.scrollTo(0, 0);
          document.addEventListener("readystatechange", (e) => {
            if (document.readyState === "complete") {
              Toast.loading("加载中...", 5, () => {}, true);
              dispatch({
                type: "getInfo",
                payload: {
                  pageNum: 1,
                },
              });
            }
          });
        } else if (pathname === "/detail") {
          Toast.loading("加载中...", 5, () => {}, true);
          setTimeout(() => {
            dispatch(
              {
                type: "getDetail",
              },
              50
            );
          });
        }
      });
    },
  },

  effects: {
    *getInfo({ payload }, { call, put, select }) {
      const { pageNum } = payload;
      const response = yield request(
        `/product/searchNewOne?page=${pageNum}&order_by=hot_desc&prd_stock=1`
      );
      yield put({
        type: "save",
        payload: {
          cList: response.data.res.products.list,
          pageNum: pageNum,
        },
      });
    },
    *queryDetail({ payload }, { call, put, select }) {
      const { querysea } = payload;
      yield put({
        type: "save",
        payload: {
          queryListDe: []
        },
      });
      const response = yield request(`/product/searchNewOne?q=${querysea}`);
      yield put({
        type: "save",
        payload: {
          queryListDe: response.data.res.products.list,
        },
      });
    },
    *getDetail({ payload }, { call, put, select }) {
      const { proid } = yield select((state) => state.content);
      if (!proid) return;
      const response = yield request(`/product/detail_v2?id=${proid}`);
      yield put({
        type: "save",
        payload: {
          proDetail: response.data.res.product
        },
      });
    },
    *getQuery({ payload }, { call, put, select }) {
      const { query } = payload;
      if (!query) return;
      const response = yield request(`/product/searchSuggest?q=${query}`);
      yield put({
        type: "save",
        payload: {
          searchList: response.data.res.list,
        }
      });
    },
  },
  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },
};
